#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <iostream>
using namespace std;

int main()
{
    // 1. 创建 soclet 连接
    int serfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(serfd == -1) {
        perror("create soclet failed");
        return 0;
    }
    else {
        cout << "create soclet successful\n";
    }

    // 2. 绑定 IP 地址和端口号
    struct sockaddr_in server_sockaddr;
    server_sockaddr.sin_family = AF_INET;//TCP/IP协议族
    server_sockaddr.sin_port = htons(8000);//端口号
    server_sockaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    int ret = bind(serfd, (struct sockaddr *)&server_sockaddr, sizeof(server_sockaddr));
    if(ret == -1) {
        perror("bind failed");
        close(serfd);
        return 0;
    }

    // 3. 发送/接收消息
    char buf[1024] = {};
    cout << "接收消息：\n";
    while(1) {
        memset(buf, 0, 1024);
        int len = recvfrom(serfd, buf, sizeof(buf), 0, NULL, NULL);
        if(len == -1) {
            perror("recv failed");
        }
        else {
            printf("[%d] %s\n", len, buf);
        }
    }

    // 4. 关闭 socket 连接
    close(serfd);

    return 0;
}